from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from ..models import Department, UserInfo, PrettyNum, Task, Order
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
import json
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
import random

class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = Order
        fields = "__all__"
        exclude = ['oid', 'admin']

def order_list(request):
    form = OrderModelForm()
    query_list = Order.objects.all().order_by('-id')
    page_object = Pagination(request, query_list)
    context = {
        'form': form,
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'order_list.html', context)

@csrf_exempt
def order_add(request):
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        form.instance.admin_id = request.session['info']['id']
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})

def order_delete(request):
    uid = request.GET.get('uid')
    if not Order.objects.filter(id=uid).exists():
        return JsonResponse({'status': False})
    Order.objects.filter(id=uid).delete()
    return JsonResponse({'status': True})

def order_detail(request):
    uid = request.GET.get('uid')
    row_object = Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'error': '数据不存在'})
    result = {
        'status': True,
        'data': {
            'title': row_object.title,
            'price': row_object.price,
            'status': row_object.status,
        }
    }
    return JsonResponse(result)